package cn.com.woxitech.dev.service;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Set;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloopen.rest.sdk.CCPRestSmsSDK;

import cn.com.woxitech.dev.common.Const;
import cn.com.woxitech.dev.dao.gen.TSmsCodeMapper;
import cn.com.woxitech.dev.model.gen.TSmsCode;
import cn.com.woxitech.dev.model.gen.TSmsCodeExample;

@Service
public class SMSCodeService {

	

	@Autowired
	private TSmsCodeMapper sMSCodeMapper;

	public TSmsCode getTSmsCodeByPhoneNum(String phoneNum) {
		TSmsCodeExample example = new TSmsCodeExample();
		example.createCriteria().andPhonenumEqualTo(phoneNum);
		List<TSmsCode> list = sMSCodeMapper.selectByExample(example);
		if (list.isEmpty()) {
			return null;
		}else {
			return list.get(0);
		}
	}

	public void insertSMSCode(TSmsCode current_code) {
		// TODO Auto-generated method stub
		sMSCodeMapper.insertSelective(current_code);
	}

	public void updateSMSCode(TSmsCode current_code) {
		// TODO Auto-generated method stub
		TSmsCodeExample example = new TSmsCodeExample();
		example.createCriteria().andPhonenumEqualTo(current_code.getPhonenum());
		sMSCodeMapper.updateByExampleSelective(current_code, example);
	}
	
	public boolean sendSMSVerifyCode(String phoneNum, String code) {
		// TODO Auto-generated method stub
		boolean isSuc= true;
		
		HashMap<String, Object> result = null;

		//初始化SDK
		CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
		
		//******************************注释*********************************************
		//*初始化服务器地址和端口                                                       *
		//*沙盒环境（用于应用开发调试）：restAPI.init("sandboxapp.cloopen.com", "8883");*
		//*生产环境（用户应用上线使用）：restAPI.init("app.cloopen.com", "8883");       *
		//*******************************************************************************
//		restAPI.init("sandboxapp.cloopen.com", "8883");
		restAPI.init("app.cloopen.com", "8883"); 
		
		//******************************注释*********************************************
		//*初始化主帐号和主帐号令牌,对应官网开发者主账号下的ACCOUNT SID和AUTH TOKEN     *
		//*ACOUNT SID和AUTH TOKEN在登陆官网后，在“应用-管理控制台”中查看开发者主账号获取*
		//*参数顺序：第一个参数是ACOUNT SID，第二个参数是AUTH TOKEN。                   *
		//*******************************************************************************
		restAPI.setAccount("8a48b5514fba2f87014fbb562a0705b5", "d1e23b43b7f24314a784c56d3907821d");
		
		//******************************注释*********************************************
		//*初始化应用ID                                                                 *
		//*测试开发可使用“测试Demo”的APP ID，正式上线需要使用自己创建的应用的App ID     *
		//*应用ID的获取：登陆官网，在“应用-应用列表”，点击应用名称，看应用详情获取APP ID*
		//*******************************************************************************
//		restAPI.setAppId("aaf98f894fba2cb2014fbb56778f024b");
		restAPI.setAppId("aaf98f894fba2cb2014fbb64ac8c0268");
		
		
		//******************************注释****************************************************************
		//*调用发送模板短信的接口发送短信                                                                  *
		//*参数顺序说明：                                                                                  *
		//*第一个参数:是要发送的手机号码，可以用逗号分隔，一次最多支持100个手机号                          *
		//*第二个参数:是模板ID，在平台上创建的短信模板的ID值；测试的时候可以使用系统的默认模板，id为1。    *
		//*系统默认模板的内容为“【云通讯】您使用的是云通讯短信模板，您的验证码是{1}，请于{2}分钟内正确输入”*
		//*第三个参数是要替换的内容数组。																														       *
		//**************************************************************************************************
		
		//**************************************举例说明***********************************************************************
		//*假设您用测试Demo的APP ID，则需使用默认模板ID 1，发送手机号是13800000000，传入参数为6532和5，则调用方式为           *
		//*result = restAPI.sendTemplateSMS("13800000000","1" ,new String[]{"6532","5"});																		  *
		//*则13800000000手机号收到的短信内容是：【云通讯】您使用的是云通讯短信模板，您的验证码是6532，请于5分钟内正确输入     *
		//*********************************************************************************************************************
//		result = restAPI.sendTemplateSMS(phoneNum,"1" ,new String[]{code,"5"});
		result = restAPI.sendTemplateSMS(phoneNum,"42492" ,new String[]{code,"5"});
		
		System.out.println("SDKTestGetSubAccounts result=" + result);
		if("000000".equals(result.get("statusCode"))){
			
			//正常返回输出data包体信息（map）
			HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
			Set<String> keySet = data.keySet();
			for(String key:keySet){
				Object object = data.get(key);
				System.out.println(key +" = "+object);
			}
		}else{
			//异常返回输出错误码和错误信息
			System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
			isSuc = false;
		}
		
		return isSuc;
	}
	public boolean sendUrl(String phoneNum, String url) {
		// TODO Auto-generated method stub
		boolean isSuc= true;
		
		HashMap<String, Object> result = null;

		//初始化SDK
		CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
		restAPI.init("app.cloopen.com", "8883"); 
		restAPI.setAccount("8a48b5514fba2f87014fbb562a0705b5", "d1e23b43b7f24314a784c56d3907821d");
		restAPI.setAppId("aaf98f894fba2cb2014fbb64ac8c0268");
		result = restAPI.sendTemplateSMS(phoneNum,"42492" ,new String[]{url,"5"});
		System.out.println("SDKTestGetSubAccounts result=" + result);
		if("000000".equals(result.get("statusCode"))){
			//正常返回输出data包体信息（map）
			HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
			Set<String> keySet = data.keySet();
			for(String key:keySet){
				Object object = data.get(key);
				System.out.println(key +" = "+object);
			}
		}else{
			//异常返回输出错误码和错误信息
			System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
			isSuc = false;
		}
		
		return isSuc;
	}
	public boolean createSMSVerifyCodeInDB(String phoneNum, String code) {
		// TODO Auto-generated method stub
		boolean result = true;
		try{
			Timestamp time = new Timestamp(System.currentTimeMillis());
			TSmsCode current_code = new TSmsCode(phoneNum, code, time);
			TSmsCode smsCode = getTSmsCodeByPhoneNum(phoneNum);
			
			if(smsCode == null ){
				//Todo 表中没有phoneNum, 插入新记录
				insertSMSCode(current_code);
			}else{
				//Todo 表中有phoneNum，更新新纪录
				updateSMSCode(current_code);
			}
		}catch(Exception ex){
			ex.printStackTrace();
			result = false;
		}
		
		return result;
	}

	public boolean validateSMSVerifyCode(String inputPhone, String inputMsgCode) {
		// TODO Auto-generated method stub
		
		boolean result = true;

		try{
			Timestamp time = new Timestamp(System.currentTimeMillis());
			TSmsCode current_code = new TSmsCode(inputPhone, inputMsgCode, time);
			TSmsCode smsCode = getTSmsCodeByPhoneNum(inputPhone);
			
			if(!(
					smsCode != null
					&&
					current_code.getCode().equals(smsCode.getCode())
					&& 
					(time.getTime() - smsCode.getTime().getTime())/1000 <= Const.SMSCODE_TIMEOUT)
					){
				result = false;
			}
			
		}catch(Exception ex){
			ex.printStackTrace();
			result = false;
		}
		
		return result;
	}
	public String generateCode() {
		StringBuilder code = new StringBuilder();
		for (int i = 0; i < 4; i++) {
			int temp = (int)(Math.random()*10);
			code.append(temp);
		}
		return code.toString();
	}

}
